"""
API数据模型
定义FastAPI的请求和响应模型
"""

from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field, ConfigDict
from enum import Enum
import time


class ModelType(str, Enum):
    """模型类型枚举"""
    DETECTION = "detection"
    SEGMENTATION = "segmentation"
    CLASSIFICATION = "classification"
    POSE = "pose"


class ModelSize(str, Enum):
    """模型大小枚举"""
    XSMALL = "xs"
    NANO = "n"
    SMALL = "s"
    MEDIUM = "m"
    LARGE = "l"
    XLARGE = "x"


class ModelStatus(str, Enum):
    """模型状态枚举"""
    AVAILABLE = "available"
    UNAVAILABLE = "unavailable"
    LOADING = "loading"
    ERROR = "error"
    MAINTENANCE = "maintenance"
    DISPATCHING = "dispatching"


class SubscriptionStatus(str, Enum):
    """订阅状态枚举"""
    ACTIVE = "active"
    PAUSED = "paused"
    CANCELLED = "cancelled"


class ServerStatus(str, Enum):
    """服务器状态枚举"""
    ONLINE = "online"
    OFFLINE = "offline"
    ERROR = "error"


# 响应模型
class BaseResponse(BaseModel):
    """基础响应模型"""
    success: bool = True
    message: str = ""
    timestamp: float = Field(default_factory=lambda: __import__('time').time())


class ErrorResponse(BaseResponse):
    """错误响应模型"""
    success: bool = False
    error_code: Optional[str] = None
    details: Optional[Dict[str, Any]] = None


# 模型相关模型
class ModelInfoResponse(BaseModel):
    """模型信息响应"""
    model_config = ConfigDict(protected_namespaces=())

    id: str
    name: str
    version: str
    model_type: ModelType
    description: str
    author: str
    size: ModelSize
    upload_time: float
    last_update: float
    status: ModelStatus
    download_url: str
    checksum: str
    server_id: str
    tags: List[str] = []
    requirements: Dict[str, str] = {}
    metrics: Dict[str, Any] = {}


class ModelsListResponse(BaseResponse):
    """模型列表响应"""
    models: List[ModelInfoResponse]
    total: int
    page: int = 1
    page_size: int = 100


class ModelCreateRequest(BaseModel):
    """创建模型请求"""
    model_config = ConfigDict(protected_namespaces=())

    name: str = Field(..., min_length=1, max_length=100)
    version: str = Field(default="1.0.0", max_length=20)
    model_type: ModelType
    description: str = Field(default="", max_length=500)
    author: str = Field(default="", max_length=100)
    size: ModelSize = ModelSize.MEDIUM
    download_url: str = Field(..., min_length=1)
    checksum: Optional[str] = None
    tags: List[str] = []
    requirements: Dict[str, str] = {}


# 订阅相关模型
class SubscriptionRequest(BaseModel):
    """订阅请求"""
    model_config = ConfigDict(protected_namespaces=())

    client_id: str = Field(..., min_length=1)
    client_name: str = Field(..., min_length=1)
    model_name: str = Field(..., min_length=1)
    model_version: str = Field(default="*")
    server_id: str = Field(..., min_length=1)
    auto_update: bool = True
    notification_channels: List[str] = ["webhook"]
    callback_url: Optional[str] = None


class SubscriptionResponse(BaseModel):
    """订阅响应"""
    model_config = ConfigDict(protected_namespaces=())

    id: str
    client_id: str
    client_name: str
    model_name: str
    model_version: str
    server_id: str
    subscribed_at: float
    last_checked: float
    status: SubscriptionStatus
    auto_update: bool
    notification_channels: List[str]
    callback_url: Optional[str]


class SubscriptionsListResponse(BaseResponse):
    """订阅列表响应"""
    subscriptions: List[SubscriptionResponse]
    total: int


# 服务器相关模型
class ServerRegisterRequest(BaseModel):
    """服务器注册请求"""
    name: str = Field(..., min_length=1, max_length=100)
    url: str = Field(..., min_length=1)
    api_key: Optional[str] = None
    check_interval: int = Field(default=1800, ge=60, le=86400)  # 1分钟到1天


class ServerResponse(BaseModel):
    """服务器响应"""
    id: str
    name: str
    url: str
    status: ServerStatus
    last_check: Optional[float]
    check_interval: int
    consecutive_errors: int


class ServersListResponse(BaseResponse):
    """服务器列表响应"""
    servers: List[ServerResponse]
    total: int


# 通知相关模型
class NotificationRequest(BaseModel):
    """通知请求"""
    model_config = ConfigDict(protected_namespaces=())

    event_type: str = Field(..., min_length=1)
    model_id: str = Field(..., min_length=1)
    model_name: str = Field(..., min_length=1)
    server_id: str = Field(..., min_length=1)
    timestamp: float = Field(default_factory=lambda: time.time())
    data: Dict[str, Any] = {}


class WebhookPayload(BaseModel):
    """Webhook载荷"""
    event: str
    model: ModelInfoResponse
    server_id: str
    timestamp: float
    signature: Optional[str] = None


# 健康检查模型
class HealthResponse(BaseModel):
    """健康检查响应"""
    status: str = "healthy"
    version: str = "1.0.0"
    timestamp: float = Field(default_factory=lambda: __import__('time').time())
    services: Dict[str, str] = {}


# 客户端相关模型
class ClientRegisterRequest(BaseModel):
    """客户端注册请求"""
    model_config = ConfigDict(protected_namespaces=())
    
    client_id: str = Field(..., min_length=1, max_length=100)
    client_name: str = Field(..., min_length=1, max_length=100)
    hostname: str = Field(..., min_length=1, max_length=100)
    ip_address: str = Field(..., min_length=1, max_length=45)
    port: int = Field(..., ge=1, le=65535)
    version: str = Field(default="1.0.0", max_length=20)
    capabilities: List[str] = []
    description: str = Field(default="", max_length=500)
    contact_info: Optional[str] = Field(default=None, max_length=200)


class ClientResponse(BaseModel):
    """客户端响应"""
    model_config = ConfigDict(protected_namespaces=())
    
    id: str
    client_id: str
    client_name: str
    hostname: str
    ip_address: str
    port: int
    version: str
    capabilities: List[str]
    description: str
    contact_info: Optional[str]
    registered_at: float
    last_seen: float
    status: str


class ClientsListResponse(BaseResponse):
    """客户端列表响应"""
    clients: List[ClientResponse]
    total: int


# 模型状态相关模型
class ModelStatusReport(BaseModel):
    """模型状态汇报"""
    model_config = ConfigDict(protected_namespaces=())
    
    client_id: str = Field(..., min_length=1)
    model_name: str = Field(..., min_length=1)
    model_type: str = Field(..., min_length=1)
    model_size: Optional[str] = None
    model_version: Optional[str] = None
    status: str = Field(..., min_length=1)
    file_path: Optional[str] = None
    file_size: Optional[int] = None
    upload_time: Optional[float] = None
    last_used: Optional[float] = None
    usage_count: int = 0
    performance_metrics: Dict[str, Any] = {}
    error_message: Optional[str] = None
    system_info: Dict[str, Any] = {}


class ModelStatusResponse(BaseResponse):
    """模型状态响应"""
    reported_at: float = Field(default_factory=lambda: __import__('time').time())


# 统计信息模型
class StatisticsResponse(BaseModel):
    """统计信息响应"""
    total_models: int = 0
    total_subscriptions: int = 0
    total_servers: int = 0
    active_subscriptions: int = 0
    online_servers: int = 0
    models_by_type: Dict[str, int] = {}
    models_by_status: Dict[str, int] = {}
    recent_activities: List[Dict[str, Any]] = []
